<?php
class TradeModel extends Model {
	protected $autoCheckFields = false;
	function Trade( $trades_response ) {
		$trades = array ();
		foreach ( $trade_response as $trade ) {
			$trades [$trade ['tid']] = $trade;
		}
		return $trades;
	}
	/**
	 * 检查SKU
	 * @param unknown $outer_sku_id
	 */
	function checkProductSku( $outer_sku_id ) {
		$proinfo = $this->getProductBySku ( $outer_sku_id );
		return $proinfo ? true : false;
	}
	/**
	 * 检查订单是否入库
	 * @param $tid
	 */
	function checkTradeChecked( $tid ) {
		return M ( 'trade' )->where ( "tid = {$tid} " )->find ();
	}
	
	/**
	 * 检查库存
	 * @param $outer_sku_id
	 */
	function getProductInventory( $outer_sku_id ) {
		$proinfo = $this->getProductBySku ( $outer_sku_id );
		return $proinfo ['proinventory'];
	}
	/**
	 * 检查余额
	 * @param $seller_nick
	 */
	function getSellerPaybalance( $seller_nick ) {
		$seller = M ( 'seller' )->where ( "nick='{$seller_nick}'" )->find ();
		return $seller ['paybalance'];
	}
	
	/**
	 * @todo 北京市
	 * 快递费用=（要计算商品总重量为550克，
	 * 没有超重，只计算浙江省的首重费用就可以了，如果超过首重重量要加上续重费用）550克不超重，
		浙江省设置的首重快递费为8元 
	 * @param $trade 交易项 array('trade')
	 * @param $ptid 快递模板ID
	 * @return $price array() 价格
	 * array(
	 *  'post' => '快递费用',
	 *  'vprice' => '商品总价',
	 *  'chengben' => vprice + post 
	 * )
	 */
	function getTradePrice( $trade, $ptid ) {
		
		if( empty( $trade ) || empty( $ptid ) ) 
		{
			Log::write( 'price.get::::'. str_replace( PHP_EOL, ' ',  var_export(  func_get_args() , true) ).'_user:'.$_SESSION['seller_nick'], LOG::INFO , '', LOG_PATH.date('y_m_d').'.price.log' );
			return false ;
		}
		$pt = D ( 'PostTemplate' );
		$weight = 0;
		$price = array();
		$products = array();
		// 根据快递代码获取快递-地区配置
		$post = array ();
		$error = array();
		$post ['base'] = M ( 'posttemplate' )->where ( " id = '{$ptid}' " )->find ();
		$post_base_sql = D()->_sql();
		$distinct = $trade['receiver_state'] ? $trade['receiver_state'] : $_POST['receiver_state']; 
		$post ['district'] = M ( 'posttemplatedistrict' )->where ( " tplid = {$post['base']['id']} AND dname='{$distinct}' " )->find ();
		//$sql = D()->_sql(). var_export( $post['district'] , true ) ;
		foreach ( $trade ['orders']['order'] as $order ) {
			$product = $this->getProductBySku ( $order ['outer_sku_id'] );
			$product_sku_sql = D()->_sql();
			Log::write( 'price.get::::getProductBySku:'. $product_sku_sql . 'SKU:'. $order ['outer_sku_id']  .'_user:'.$_SESSION['seller_nick'], LOG::INFO , '', LOG_PATH.date('y_m_d').'.price.log' );
			//echo D()->_sql();
			if( empty($product) ) {
				Log::write( 'price.get::::posttemplate:'. $post_base_sql .'_user:'.$_SESSION['seller_nick'], LOG::INFO , '', LOG_PATH.date('y_m_d').'.price.log' );
				Log::write( 'price.get::::getProductBySku:'. $product_sku_sql . 'SKU:'. $order ['outer_sku_id']  .'_user:'.$_SESSION['seller_nick'], LOG::INFO , '', LOG_PATH.date('y_m_d').'.price.log' );
				return false ;
				break;
			}
			$weight += $product ['proweight'] * $order['num'] ;	//商品重量
			$price['cprice'] += $product['cprice'] * $order[ 'num' ];	//系统成本价
			$price['vprice'] += $product['vprice'] * $order[ 'num' ];	//会员价
		}
		
		
		// 存在地区价格
		// <
		// 起步重量
		// 价格为起步价（地区起步价>>默认起步价）
		//$sql .= 'weight: '. $weight ;
		if ($post ['district']) {
			$price['post'] = ($weight < $post ['base'] ['startweight']) ? ($post ['district'] ['ptdstartprice']) : 
			($post ['district'] ['ptdstartprice'] + $post ['district'] ['ptdincreaseprice'] * ceil ( ($weight - $post ['base'] ['startweight']) / $post ['base'] ['increaseweight'] ));
		} else {
			
			$price['post'] = ($weight < $post ['base'] ['startweight']) ? ($post ['base'] ['startprice']) : ($post ['base'] ['startprice'] + $post ['base'] ['increaseprice'] * ceil ( ($weight - $post ['base'] ['startweight']) / $post ['base'] ['increaseweight'] ));
		}
		$price['cost'] = $price['vprice'] + $price['post'] ;	//用户成本价
		//$price['sql']	= $sql;
		
		return $price ;
	}
	function getTradeByTid( $tid ) {
		return M('Trade')->where( "tid = {$tid} OR systids like '%{$tid}%' " )->find();
	}
	/**
	 * 检查订单是否已入库
	 * @param $tid	订单ID
	 * @param string $tids	合并的订单ID
	 * @return Ambigous <mixed, boolean, NULL, multitype:>
	 */
	function filterTrade( $tid, $tids = '' ){
		if( $tids ) {
			return M('Trade')->where( "tid = {$tid} OR tid IN ( {$tids} )' " )->find();
		}else {
			return M('Trade')->where( "tid = {$tid} OR systids like '%{$tid}%' " )->find(); 
		}
	}
	function getProductBySku( $outer_sku_id ) {
// 		$r = M ( 'productsku' )->where ( "prosku = '{$outer_sku_id}' " )->find ();
// 		return $r ;
		$d  = D('ProductView')->where ( "prosku = '{$outer_sku_id}' " )->find (); 
		return $d ;
	}
	
	/**
	 * 买家订单数
	 * @param $buyer_nick
	 */
	function getTradeCountByBuyer ( $buyer_nick, $sysstatus=null ) {
		$where =  null === $sysstatus ? '' : " AND sysstatus='{$sysstatus}'" ;
		return D('Trade')->where("buyer_nick='{$buyer_nick}' {$where}")->count();
	}
	
	//减少库存
	/**
	 * 更新库存
	 * @param unknown $skuid	系统skuid
	 * @param unknown $proinventory	更新量
	 * @param $type	'-' | '+'
	 * @return boolean
	 */
	public function updateProinventory ( $prosku , $num, $nick, $type , $logtext, $trans=false ){
		$ps = D('Productsku');
		$psl = D('Productskulog');
		
		if( $prosku && $num && $type ) {
			$productsku = $this->getProductBySku( $prosku );
			if( empty( $productsku )) return false;
			if( $type == '-' && $productsku['proinventory'] < $num ) return false;
			
			if( $trans ) $ps->startTrans();
			$proinventory = $productsku['proinventory'] + intval( $type .'1' * $num) ; 
			$data['proinventory'] = $proinventory;
			//echo $proinventory;
			$vo = $ps->where ( "prosku='{$prosku}'" )->save ( $data );
			
			$psl->addlog( $prosku, $productsku['skuid'], $proinventory, $nick , $num, $type , $logtext );
			if ($vo) {
				if( $trans ) $ps->commit();
				return true;
			} else {
				if( $trans ) $ps->rollback();
				return false;
			}
		}else {
			return false ;
		}
	}
	
}